import { supabase } from "./supabase";

// 团队类型定义
export interface TeamMemberType {
    email: string;
    id: string;
    team_id: string;
    user_id: string;
    role: string;
    status: string;
    updated_at: string;
    remark: string;
    joined_at: string;
    invited_at?: string;
    invited_by?: string;
    inviter?: string;
}

export const getUserTeam = async (user_id: string) => {
    const data: { data: TeamMemberType | null, error: Error | null } = await supabase
        .from('team_members')
        .select('*')
        .eq('user_id', user_id)
        .single();
    return data;
}

export const getTeamMembers = async (team_id: string) => {
    const data: { data: TeamMemberType[] | null, error: Error | null } = await supabase
        .from('team_members')
        .select('*')
        .eq('team_id', team_id);
    return data;
}
type CreateTeamMemberType = {
    team_id: string;
    user_id: string;
    role: string;
    email: string;
    status: 'active' | 'invited' | 'inactive';
    invited_by?: string;
    inviter?: string;
}
export const createTeamMember = async ({ team_id, user_id, role, email, status, invited_by, inviter }: CreateTeamMemberType) => {
    const now = new Date().toISOString();
    const data = await supabase
        .from('team_members')
        .insert({
            team_id,
            user_id,
            email,
            role,
            status,
            inviter,
            invited_at: now,
            invited_by,
            joined_at: now,
            updated_at: now,
        })
        .select()
        .single();
    return data;
}

export const updateTeamMember = async ({ status, user_id }: { status: 'active' | 'invited' | 'inactive', user_id: string }) => {
    const now = new Date().toISOString();
    const data = await supabase
        .from('team_members')
        .update({
            status,
            joined_at: now,
            updated_at: now,
        })
        .eq('user_id', user_id)
        .select()
        .single();
    return data;
}


export const deleteTeamMember = async (user_id: string) => {
    const data = await supabase
        .from('team_members')
        .delete()
        .eq('user_id', user_id)
        .select()
        .single();
    return data;
}


